package servlet;

import model.Goods;
import model.Order;
import model.User;
import service.GoodsService;
import service.OrderService;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@WebServlet(name = "order_list", urlPatterns = "/order_list")
public class OrderListServlet extends HttpServlet {
    private OrderService oService = new OrderService();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            request.setAttribute("failMsg", "请先登录！");
            request.getRequestDispatcher("/user_login.jsp").forward(request, response);
            return;
        }

        try {
            Goods g = new Goods();
            GoodsService gService = new GoodsService();

            //通过前端传来的字段id1:amount1,id2:amount2，获取当前商品id和amount
            String[] ids = request.getParameterValues("id");
            String[] quantities = request.getParameterValues("quantity");
            if (ids != null && quantities != null && ids.length == quantities.length) {
                for (int i = 0; i < ids.length; i++) {
                    int productId = Integer.parseInt(ids[i]);
                    int amount = Integer.parseInt(quantities[i]);
                    Order singleOrder = new Order();
                    singleOrder.setSeller_id(gService.getUserIdById(productId));
                    singleOrder.setUser(user);
                    singleOrder.setProduct_id(productId);
                    singleOrder.setAmount(amount);
                    float price = gService.getPriceById(productId) * amount;
                    singleOrder.setBuy_price(price);
                    singleOrder.setCode(String.valueOf(System.currentTimeMillis()) + user.getUsername());
                    oService.addOrder(singleOrder);

                    //更新商品数据库
                    Goods good = gService.getGoodsById(productId);
                    good.setInventory(good.getInventory() - 1);
                    gService.update(good);

                    //测试
                    if (good.getInventory() == 0) {
                        good.setIs_removed(true);
                        gService.update(good);
                    }
                }
            }

            //获取list
            List<Order> list_buy = oService.selectAll(user.getId());
            List<Order> list_sell = oService.selectAllBySellerId(user.getId());
            List<Order> allOrders = new ArrayList<>();
            if (list_buy != null) allOrders.addAll(list_buy);
            if (list_sell != null) allOrders.addAll(list_sell);

            request.getSession().removeAttribute("order");
            request.setAttribute("msg", "订单支付成功！");

            //将获取的list表格通过orderList字段传给前端
            request.getSession().setAttribute("orderListAll", allOrders);
            request.getSession().setAttribute("orderListBuy", list_buy);
            request.getSession().setAttribute("orderListSell", list_sell);
            request.getRequestDispatcher("/goods_cart.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "处理订单时发生错误：" + e.getMessage());
            request.getRequestDispatcher("/goods_cart.jsp").forward(request, response);
        }
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

